<template>
<m-modal width="60%" ref="modalRef" title="添加成员" @ok="handleOk">
  <m-table
  ref="tableRef"
  :row-selection="rowSelection"
  :api="userListExcludeRoleId" 
  :columns="columns" 
  :beforeFetch="handleBeforeFetch">
  <template #tableToolbarLeft>
    <a-input-search
      allowClear
      v-model:value="keywords"
      placeholder="请输入关键字（用户名、姓名）"
      enter-button="查询"
      @search="onSearch"
    />
  </template>
  </m-table>
</m-modal>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { userListExcludeRoleId, saveUserRole } from '/@/api/sys/role'
import { message } from 'ant-design-vue';
const tableRef=ref()
const keywords = ref('')
const columns = ref([{
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
  }, {
    title: '姓名',
    dataIndex: 'realName',
    key: 'realName',
}, {
    title: '手机号',
    dataIndex: 'mobilePhone',
    key: 'mobilePhone',
}])
const modalRef = ref();
const currentRecord = ref<any>(null);
const selectedRowKeys = ref<string[]>([]);
const rowSelection = {
  onChange(keys: string[]){
    selectedRowKeys.value = keys;
  }
}
const handleBeforeFetch = (params: any)=>{
  return {
    ...params,
    roleId: currentRecord.value?.id,
    keywords: keywords.value || undefined
  }
}
const onSearch = () =>{
  tableRef.value?.reload()
}
const handleOk = () =>{
  if(selectedRowKeys.value.length>0){
    const params = selectedRowKeys.value.map(userId=>{
      return {
        userId,
        roleId: currentRecord.value?.id
      }
    })
    saveUserRole(params).then(()=>{
      message.success('添加成功！')
      tableRef.value?.reload()
    })
  }else{
    message.warn('请至少选择一个用户！')
  }
}
defineExpose({
  show(record: any) {
    currentRecord.value = record;
    modalRef.value?.openModal()
  }
})
</script>
<style lang="less" scoped>

</style>